<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    chartData: {
      type: Object,
      required: false
    }
  },
  watch:{
    chartData: {
      deep: true,
      handler(val) {
        this.initChart()
      }
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')

      this.chart.setOption( {
        backgroundColor: '#ffffff',
        tooltip: {
          trigger: 'axis',
          show: true,
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        legend: {
          show:false
        },
        grid: {
          left: '1%',
          right: '10%',
          top: '1%',
          bottom: '0%',
          containLabel: true
        },
        xAxis: [{
          splitLine: {
            show: false
          },
          type: 'value',
          show: false,
        }],
        yAxis: [{
          splitLine: {
            show: false
          },
          axisLine: { //y轴
            show: false
          },
          type: 'category',
          axisTick: {
            show: false
          },
          inverse: true,
          data: this.chartData.name,
          axisLabel: {
            color: '#303133',
            fontSize: 14,
          }
        }],
        series: [{
          name: '报警次数',
          type: 'bar',
          barWidth: 20, // 柱子宽度
          label: {
            show: true,
            position: 'right', // 位置
            color: '#303133',
            fontSize: 14,
            distance: 15, // 距离
            formatter: '{c} 次' // 这里是数据展示的时候显示的数据
          }, // 柱子上方的数值
          itemStyle: {
            barBorderRadius: [0, 0, 0, 0], // 圆角（左上、右上、右下、左下）

            color: '#419fff'
          },
          data: this.chartData.value
        }, ]
      })
    }
  }
}
</script>
